/* eslint-disable import/no-dynamic-require */
const path_ = eval('require')('path');
const fs = eval('require')('fs');
// 用于页面和应用间的信息传递
const { ipcMain, BrowserWindow } = eval('require')('electron');
// 处理普通前端方法（偏向于定制化 api）
let fetchEventDear = require('./fetchEvenDear/fetchEvenDear.js');

let winSetting = {};

// todo : 加载前事件可以在调用该函数前调用，将该函数作为回调运行
const createWin = (app) => {
    const {
        basePath,
        appAsar,
    } = require('../../foreEndApi/rebasePath')();
    if (fs.existsSync(path_.join(basePath, 'winSetting.json'))) {
        winSetting = eval('require')(path_.join(basePath, 'winSetting.json'));
    } else {
        winSetting = eval('require')('./../../winSetting.json');
    }
    const win = new BrowserWindow(winSetting.window);
    if (winSetting.baseUrl[0] === '$') {
        win.loadFile(
            path_.join(basePath, winSetting.baseUrl.substring(1)),
        );
    } else {
        win.loadURL(winSetting.baseUrl);
    }
    win.webContents.on('did-finish-load', () => {
        if (winSetting.dev) {
            win.webContents.openDevTools();
        }
        win.webContents.executeJavaScript(`
                window.require_ = function(path) { 
                    var base = "${(appAsar || basePath).replace(/\\/g, '\\\\')}";
                    return require(base + "\\\\" + path); 
                };
                window.process.resourcesPath = process.resourcesPath;
                window.fetchEvent = require_('foreEndApi\\\\fetchEvent.js');
                window.fetchEvent.fetchEventApi = window.fetchEvent.fetchEventApi(require('electron'));
                /*window.fetchEvent.dialog = window.fetchEvent.dialog(require('electron'));*/
                window.fetchEvent.initSomeElectronApi(require('electron'));
            `.split('\n').map(_ => _.trim()).join(';'));
        // todo : 加载完成事件可以放在这里
    });
    // todo : 加载中事情可以放在这里
    win.on('closed', () => {
        app.exit();
    });
    return win;
};

// const dearBrowserAction = (event, actionList) => {
//     let act = () => {
//     };
//     JSON.parse(actionList || []).reverse().forEach((action) => {
//         act = actions[action.name].bind(null, action.param, act);
//     });
//     act();
// };

/**
 * 整个浏览器方面的事件及处理入口
 * @param app       用于关闭和退出应用
 * @param config    配置文件，从 main.js 中获取到
 */
module.exports = (app) => {
    // todo : 这个 win 好像没用，只是在重启时用于销毁实例使用
    const win = createWin(app);
    fetchEventDear = fetchEventDear(win);
    ipcMain.on('fetchFore', (e, obj) => {
        fetchEventDear(e, obj);
    });
    // todo : 这个应该是用于重启重新应用配置时使用的通信
    ipcMain.on('quit', () => {
        app.quit();
    });
    // ipcMain.on('browserAction', (e, obj) => {
    //     dearBrowserAction(e, obj);
    // });
};
